package com.rongshu.view.userInfo.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.mediaPlayer.activity.AudiobookPlayerActivity;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.service.PlayerService;
import com.rongshu.view.userInfo.adapter.EnshrineAdapter;
import com.rongshu.view.userInfo.entity.EnshrineInfo;
import com.rongshu.view.userInfo.iview.EnshrineArticleView;
import com.rongshu.view.userInfo.listener.OnEnshrineItemListener;
import com.rongshu.view.userInfo.presenter.EnshrineArticlePresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.toast.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;
import static com.rongshu.utils.UserInfoUtils.getUserId;

public class EnshrineVoiceFragment extends BaseFragment<EnshrineArticlePresenter> implements EnshrineArticleView, OnEnshrineItemListener {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;

    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private EnshrineAdapter adapter = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //refresh,load
    private boolean isrefresh = true;
    //intent
    private Intent intent = null;
    //position
    private int position = 0;
    //request
    private final int REQUEST_SINGLE = 0x01;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_enshrine_voice_view;
    }

    @Override
    protected void initViews() {
        //set presenter
        setPresenter(new EnshrineArticlePresenter(getActivity()), this);
        //layoutmanager
        manager = new LinearLayoutManager(getActivity());
        //adapter
        adapter = new EnshrineAdapter(getActivity(),true);
        adapter.setOnEnshrineItemListener(this);
        //recyclerview
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                getMyCollect();
                refreshlayout.resetNoMoreData();
                refreshlayout.finishRefresh(2000, false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getMyCollect();
                refreshlayout.finishLoadmore(2000, false);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * 我的收藏
     */
    private void getMyCollect() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 3);//分类(1文章 2帖子 3有声)
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getMyCollect((int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }


    /**
     * 收藏,取消收藏
     */
    private void collectArticle(int contribute_id) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getActivity());
            return;
        }
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 3);//(1文章 2帖子 3有声)
        map.put("content_id", contribute_id);
        presenter.getIsCollect(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("content_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SINGLE://有声文章返回
                    AudiobookDetailsResponse.ResponseBean bean = (AudiobookDetailsResponse.ResponseBean) data.getSerializableExtra(Constant.INTENT_DATA);
                    if (bean != null) {
                        int isCollect = bean.getIsCollect();
                        if (isCollect == 0) {//已经取消了收藏
                            adapter.getEnshrineInfos().remove(position);
                            adapter.notifyDataSetChanged();
                            int count = adapter.getItemCount();
                            if (count == 0) {
                                refreshLayout.setVisibility(View.GONE);
                                layout_empty.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 我的收藏列表
     *
     * @param enshrineInfo
     */
    @Override
    public void onMyCollect(EnshrineInfo enshrineInfo) {
        if (enshrineInfo.getErrCode() == 0) {
            List<EnshrineInfo.ResponseBean> list = enshrineInfo.getResponse();
            if (adapter != null) {
                if (isrefresh) {
                    refreshLayout.finishRefresh();
                    if (list == null || list.isEmpty()) {
                        refreshLayout.setVisibility(View.GONE);
                        layout_empty.setVisibility(View.VISIBLE);
                    } else {
                        refreshLayout.setVisibility(View.VISIBLE);
                        layout_empty.setVisibility(View.GONE);
                        adapter.setEnshrineInfos(list);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    if (list == null || list.isEmpty()) {
                        refreshLayout.finishLoadmoreWithNoMoreData();
                    } else {
                        refreshLayout.finishLoadmore();
                        adapter.addEnshrineInfos(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        } else {
            toast(enshrineInfo.getErrMsg());
        }
    }

    /**
     * 收藏，取消收藏
     *
     * @param iNetBean
     */
    @Override
    public void onIsCollect(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            adapter.getEnshrineInfos().remove(position);
            adapter.notifyDataSetChanged();
            int count = adapter.getItemCount();
            if (count == 0) {
                refreshLayout.setVisibility(View.GONE);
                layout_empty.setVisibility(View.VISIBLE);
            }
        } else {
            toast(iNetBean.getErrMsg());
        }
    }

    @Override
    public void onItemClick(int position, final int contribute_id) {
        this.position = position;
        if (XXPermissions.isHasPermission(getActivity(), Manifest.permission.SYSTEM_ALERT_WINDOW)) {
            intent = new Intent(getActivity(), AudiobookPlayerActivity.class);
            intent.putExtra(Constant.INTENT_DATA, contribute_id);
            startActivityForResult(intent, REQUEST_SINGLE);
        } else {
            XXPermissions.with(getActivity()).permission(Manifest.permission.SYSTEM_ALERT_WINDOW).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    intent = new Intent(getActivity(), AudiobookPlayerActivity.class);
                    intent.putExtra(Constant.INTENT_DATA, contribute_id);
                    startActivityForResult(intent, REQUEST_SINGLE);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    toast(getString(R.string.audio_book_play_permission));
                }
            });
        }
    }

    @Override
    public void onItemCancleEnshrineClick(int position, int contribute_id) {
        this.position = position;
        collectArticle(contribute_id);
    }
}
